//    Copyright (C) Clear Office.  All rights reserved.
using System;
using System.Deployment.Application;
using System.Diagnostics;
using System.Reflection;
using System.Threading;
using System.Windows;
using System.Windows.Threading;

using Office.Spreadsheet.AnalysisToolPak;
using Office.Spreadsheet.StandardAddIn;
using Office.Spreadsheet.UI;
using System.Globalization;

namespace Office.Spreadsheet
{
    /// <summary>
    /// Interaction logic for MyApp.xaml
    /// </summary>

    public partial class SpreadsheetApplication
    {
        public SpreadsheetApplication()
        {

            

#if DEBUG
            ForcedCulture.ForceLanguage();
#if FORCE_FRENCH
            Thread.CurrentThread.CurrentUICulture = new CultureInfo("fr-fr");
            Thread.CurrentThread.CurrentCulture = new CultureInfo("fr-fr");
#endif
#if FORCE_GB
            Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-gb");
            Thread.CurrentThread.CurrentCulture = new CultureInfo("en-gb");
#endif
#if HEAVY_TRACE
            //\\Thread.CurrentThread.CurrentUICulture = new CultureInfo("fr");
            Debug.Listeners.Add(DebugTraceListener.Instance);
            Debug.WriteLine("Added listener " + DebugTraceListener.Instance.FileName);
            //Debug.Listeners.Add(new EventLogTraceListener(new EventLog("Clear Office Spreadsheet")));
#endif
#endif

            Functions.FunctionManager.AddAddIn(typeof(TextFunctions).Assembly);
            Functions.FunctionManager.AddAddIn(typeof(EngineeringFunctions).Assembly);
        }

        void OnStartup(object sender, StartupEventArgs args)
        {
            Debug.WriteLine(Assembly.GetEntryAssembly().FullName);
#if !PERF_TEST
            SpreadsheetSplashWindow splashWindow = null;
            var ev = new ManualResetEvent(false);
            var thread = new Thread(new ThreadStart(delegate
            {
                splashWindow = new SpreadsheetSplashWindow();
#if !NOSPLASH
                splashWindow.Show();
#endif
                ev.Set();
                System.Windows.Threading.Dispatcher.Run();
               
            }));
            thread.SetApartmentState(ApartmentState.STA);
            thread.Start();
            ev.WaitOne();
#endif

            try
            {
                Debug.WriteLine("Before main window created" + DateTime.Now);
                Window w = new SpreadsheetWindow();
                Debug.WriteLine(w.GetType().Assembly.FullName);
                Debug.WriteLine(typeof (int).Assembly.FullName);
                WindowInfo.InitializeWindow(w);
                w.Closing += onWindowClosing;
                w.Loaded += new RoutedEventHandler(wLoaded);
#if LAYOUT_TEST
                w.Loaded += w_Loaded;
#endif
                Debug.WriteLine("main window created" + DateTime.Now);
                w.Show();
#if PERF_TEST
                DispatcherTimer timer = new DispatcherTimer(DispatcherPriority.SystemIdle);
                timer.Interval = new TimeSpan(0, 0, 0, 0, 1);
                timer.Tick += delegate
                {
                    Shutdown();
                };
                timer.Start();
#endif
                w.Activate();
                Debug.WriteLine("main window shown" + DateTime.Now);
            }
            catch (Exception e)
            {
#if !PERF_TEST
                splashWindow.Dispatcher.BeginInvokeShutdown(DispatcherPriority.Normal);

                MessageBox.Show(e.ToString());
#endif
                return;
            }
#if !PERF_TEST
            Debug.WriteLine("Closing splash window");
splashWindow.Dispatcher.BeginInvokeShutdown(DispatcherPriority.Normal);
#endif                
        }

        static void wLoaded(object sender, RoutedEventArgs e)
        {
            Thread thread = new Thread((new ThreadStart(delegate
                                                            {
#if DEBUG
                                                                if (!(sender is SpreadsheetWindow))
                                                                    return;
#endif
								SpreadsheetWindow spreadsheetWindow = (SpreadsheetWindow)sender;
                                string[] cmdLineArgs = Environment.GetCommandLineArgs();
								try
								{
									for (int i = 1; i < cmdLineArgs.Length; i++)
									{
										spreadsheetWindow.openFile(cmdLineArgs[i]);
									}
								}
								catch (Exception)
								{
									//\\spreadsheetWindow.onNew(spreadsheetWindow, null);
								}

                                                                Thread.Sleep(2000);
                                                                if (!ApplicationDeployment.IsNetworkDeployed)
                                                                    return;
                                                                if (

                                                                    ApplicationDeployment.CurrentDeployment.
                                                                        CheckForUpdate())
                                                                {
                                                                    var r = MessageBox.Show(
                                                                        "A new version is available, would you like to update?",
                                                                        "", MessageBoxButton.YesNo);
                                                                    if (r == MessageBoxResult.Yes)
                                                                    {
                                                                        if 
                                                                            (ApplicationDeployment.CurrentDeployment.Update())
                                                                        MessageBox.Show(
                                                                            "Update complete, please restart Spreadsheet");
                                                                    }
                                                                }
                                                            })));
            thread.Start();
        }

#if LAYOUT_TEST
        void w_Loaded(object sender, RoutedEventArgs e)
        {
           // return;
            SpreadsheetWindow w = (SpreadsheetWindow) sender;
            w.Width = 200;
            DispatcherTimer timer = new DispatcherTimer(DispatcherPriority.SystemIdle);
            timer.Interval = new TimeSpan(0, 0, 0, 0,200);
            timer.Tick += delegate { w.Width += 1; Debug.WriteLine(w.Width);
            if (w.Width > 1500)
            timer.Stop();};

            timer.Start();
        }
#endif

        static void onWindowClosing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            try
            {
                WindowInfo.StoreWindow((Window)sender);
            }
            catch
            { }
        }


        void OnDispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
        {
            Debug.WriteLine("INTERNAL ERROR");
            Debug.WriteLine(e.Exception);
            Debug.WriteLine(e.Exception.StackTrace);
            Debug.Assert(false, e.Exception.ToString());
#if DEBUG
            System.Diagnostics.Contracts.Contract.Assert(false);
#endif
            //\\ MessageBox.Show(e.Exception.Message);
            e.Handled = true;
        }
    }
}